<template>
    <div class="w-full h-full p-6">
        <h1 class="text-4xl font-bold mb-4">My PlayList</h1>
      <el-button @click="()=>{audios.setAudioPlayList(musicList)}">播放歌单</el-button>
        <div v-if="listData">
            <el-table :data="listData" max-height="400" class="w-full">
                <el-table-column label="歌曲">
                    <template #default="scope">
                        <div class="flex items-center hover:cursor-pointer">
                            <div @click="handleTrackClick(scope.row, scope.$index)" class="flex flex-1">
                                <el-avatar :src="scope.row.song_pic" alt="" class="mr-2" />
                                <div class="mt-2">{{ scope.row.song_name }}</div>
                            </div>

                            <div class="flex-none mr-10">
                                <el-icon @click="() => { removeFromPlaylist(scope.row, scope.$index) }"
                                    class=" hover:cursor-context-menu">
                                    <CloseBold />
                                </el-icon>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue'
import { getPlayListById, getMusicUrl, removePlaylist } from '../boot/requests'
import { useAudioPlayListStore, useAudioPlayer, player as playerRef } from '@/stores/counter';

const audios = useAudioPlayListStore();
const user_id = ref(localStorage.getItem('userId'));
const listData = ref([]);
const player = ref('audioPlayer')
const musicList = ref([])
const getMyPlaylist = async (user_id) => {
    try {
        console.log('=======user_id', user_id)
        console.log(localStorage.getItem('userId'))
        const res = await getPlayListById(user_id);
        const data = res.data;

        if (data.code === 200) {
            listData.value = data.data;
            console.log(listData.value);

            const promises = listData.value.map(async (item) => {
                const song_id = item.song_id;
                const urlRes = await getMusicUrl(song_id);
                const song_url = urlRes.data.code === 200 ? urlRes.data.data[0].url : null;
                return {
                    song_id: item.song_id,
                    name: item.song_name,
                    url: song_url,
                };
            });

          musicList.value = await Promise.all(promises);
        }
    } catch (error) {
        console.error('Error fetching playlist or music URLs:', error);
    }
};

function handleTrackClick(row, index) {
    playerRef.value.currentPlayIndex = index
    if (playerRef.value.isPlaying) {
        playerRef.value.pause()
    }
    playerRef.value.play()
    setTimeout(() => {
        playerRef.value.play()
    }, 1000)
}

function removeFromPlaylist(row, index) {
    console.log(row)
    let payload = {
        user_id: user_id.value,
        song_id: row.song_id
    }
    removePlaylist(payload).then(res => {
        let data = res.data;
        if (data.code === 200) {
            ElMessage.success('Remove from playlist successfully');
            listData.value.splice(index, 1);
        }
        else {
            ElMessage.error('Remove from playlist failed');
        }
    })
}

getMyPlaylist(localStorage.getItem('userId'));
</script>
<style scoped></style>
